<?php
declare(strict_types=1);

namespace App\AdminApi\Modular\System\Search;

use App\Common\Modular\System\Model\SmsModel;
use Core\Basics\BasicsSearch;
use Core\Package\Export\Excel;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Collection;
use Zms\Unit\Is;
use App\Common\Query\Query;

class SmsSearch extends BasicsSearch
{

    public function query(): Builder
    {
        return SmsModel::query()
            ->when(isset($this->where['phone']) && Is::notEmpty($this->where['phone']), function (Builder $query) {
                Query::LikeSearch($query, 'phone', $this->where['phone']);
            })
            ->when(isset($this->where['status']) && Is::notEmpty($this->where['status']), function (Builder $query) {
                $query->where('status', $this->where['status']);
            })
            ->when(isset($this->where['template_id']) && Is::notEmpty($this->where['template_id']), function (Builder $query) {
                $query->where('template_id', $this->where['template_id']);
            })
            ->orderByRaw($this->order);
    }


    /**
     * 导出短信记录
     * @param string $filename
     * @return array
     */
    public function export(string $filename): array
    {
        $ExportData = [];
        $this->query()->chunk(200, function (Collection $users) use (&$ExportData) {
            foreach ($users->toArray() as $item) {
                $ExportData[] = [
                    $item['phone'],
                    $item['status'] ? '成功' : '失败',
                    $item['content'],
                    date("Y-m-d H:i:s", $item['send_at'])
                ];
            }
        });
        return Excel::export($filename, ['手机号', '状态', '短信内容', '发送时间'], $ExportData);
    }
}